<template>
    <div>
        <!-- 上传 Excel 文件 -->
        <el-upload class="upload-demo" 
            :before-upload="beforeUpload">
            <el-button type="primary">Click to upload</el-button>
            <template #tip>
                <div class="el-upload__tip">
                    Upload an Excel file to display its data.
                </div>
            </template>
        </el-upload>

        <!-- Tabs 切换不同的 sheet -->
        <el-tabs v-if="sheets.length" v-model="activeSheet">
            <el-tab-pane 
                v-for="(sheet, index) in sheets" 
                :key="index" 
                :label="sheet.name" 
                :name="sheet.name">
                <!-- 表格展示当前 sheet 的数据 -->
                <el-table 
                    v-if="sheet.data.length" 
                    :data="sheet.data" 
                    style="width: 100%; margin-top: 20px;" 
                    border>
                    <el-table-column
                        v-for="header in sheet.headers"
                        :key="header"
                        :prop="header"
                        :label="header"
                        align="center">
                        <template #default="{ row, $index }">
                            <el-input 
                                v-model="row[header]" 
                                size="small" 
                                @change="onCellChange(row, header, $index)">
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

        <!-- 导出按钮 -->
        <el-button 
            v-if="sheets.length" 
            type="success" 
            style="margin-top: 20px;" 
            @click="exportExcel">
            Export Modified Data
        </el-button>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from "xlsx";

interface SheetData {
    name: string; // Sheet 名称
    headers: string[]; // 表头
    data: any[]; // 表格数据
}

const sheets = ref<SheetData[]>([]); // 所有 sheet 数据
const activeSheet = ref<string>(""); // 当前激活的 sheet 名称
let originalFileName = ""; // 原始文件名

// 上传前处理 Excel 文件
function beforeUpload(file: File) {
    originalFileName = file.name.split(".")[0]; // 获取文件名（不含扩展名）
    const reader = new FileReader();
    reader.onload = (event: ProgressEvent<FileReader>) => {
        const arrayBuffer = event.target?.result;
        if (!arrayBuffer) {
            ElMessage.error('Failed to read the file.');
            return;
        }

        // 读取 Excel 数据
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });
        sheets.value = []; // 清空之前的 sheet 数据

        workbook.SheetNames.forEach(sheetName => {
            const worksheet = workbook.Sheets[sheetName];

            // 处理合并单元格
            handleMergedCells(worksheet);

            // 转换为 JSON 数据
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: '' }) as any[][];

            // 处理左侧作为表头的情况
            // const transformedData = transformLeftHeaderToTopHeader(jsonData);

            sheets.value.push({
                name: sheetName,
                headers: transformedData.headers,
                data: transformedData.data
            });
        });

        if (sheets.value.length > 0) {
            activeSheet.value = sheets.value[0].name; // 默认激活第一个 sheet
            ElMessage.success('Excel data loaded successfully!');
        } else {
            ElMessage.warning('The Excel file is empty.');
        }
    };
    reader.readAsArrayBuffer(file);

    return false; // 阻止默认上传行为
}

// 将左侧表头转换为顶部表头
function transformLeftHeaderToTopHeader(data: any[][]): { headers: string[]; data: any[] } {
    if (data.length === 0) return { headers: [], data: [] };

    const headers = data.map(row => row[0]); // 提取第一列作为表头
    const transformedData = data[0].slice(1).map((_, colIndex) => {
        const rowData: any = {};
        headers.forEach((header, rowIndex) => {
            rowData[header] = data[rowIndex][colIndex + 1]; // 跳过第一列
        });
        return rowData;
    });

    return { headers, data: transformedData };
}

// 处理合并单元格的函数
function handleMergedCells(worksheet: XLSX.WorkSheet) {
    const merges = worksheet['!merges'] || []; // 获取合并单元格信息

    merges.forEach(merge => {
        const startRow = merge.s.r; // 起始行
        const endRow = merge.e.r; // 结束行
        const startCol = merge.s.c; // 起始列
        const endCol = merge.e.c; // 结束列

        // 获取合并单元格的值
        const cellAddress = XLSX.utils.encode_cell({ r: startRow, c: startCol });
        const cellValue = worksheet[cellAddress]?.v;

        // 填充合并单元格的值到所有相关单元格
        for (let row = startRow; row <= endRow; row++) {
            for (let col = startCol; col <= endCol; col++) {
                const address = XLSX.utils.encode_cell({ r: row, c: col });
                if (!worksheet[address]) {
                    worksheet[address] = { t: 's', v: cellValue }; // 填充值
                }
            }
        }
    });
}

// 单元格值修改事件
function onCellChange(row: any, header: string, index: number) {
    console.log(`Row ${index + 1}, Column "${header}" changed to:`, row[header]);
    ElMessage.success(`Updated value in Row ${index + 1}, Column "${header}"`);
}

// 导出 Excel 文件
function exportExcel() {
    const workbook = XLSX.utils.book_new(); // 创建新的工作簿

    sheets.value.forEach(sheet => {
        const worksheet = XLSX.utils.json_to_sheet(sheet.data); // 将数据转换为工作表
        XLSX.utils.book_append_sheet(workbook, worksheet, sheet.name); // 将工作表添加到工作簿
    });

    // 生成文件名：原始文件名 + 时间戳
    const timestamp = new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14);
    const fileName = `${originalFileName}_${timestamp}.xlsx`;

    // 导出文件
    XLSX.writeFile(workbook, fileName);
    ElMessage.success(`File exported as ${fileName}`);
}
</script>